<template>
  <div id="userDetail">
    <el-row :gutter="5" type="flex" v-loading="loading">
      <el-col :span="13">
        <el-card
          class="box-card"
          style="border-radius: 10px; background-color: #ffffffad"
        >
          <el-descriptions title="个人信息" :column="2" border>
            <template slot="extra">
              <el-button
                type="success"
                size="small"
                plain
                round
                @click="showUpdateDialog"
                >修改</el-button
              >
              <el-button
                type="warning"
                size="small"
                plain
                round
                @click="initResetDialog"
                >重置密码</el-button
              >
            </template>
            <el-descriptions-item
              label="昵称"
              label-class-name="my-label"
              content-class-name="my-content"
              >{{ nickName }}</el-descriptions-item
            >
            <el-descriptions-item
              label="邮箱"
              label-class-name="my-label"
              content-class-name="my-content"
              >{{ mail }}</el-descriptions-item
            >
            <el-descriptions-item
              label="性别"
              label-class-name="my-label"
              content-class-name="my-content"
              >{{ sex }}</el-descriptions-item
            >
          </el-descriptions></el-card
        >

        <!-- 账户一览表格 -->
        <el-card
          v-if="showUsers"
          class="box-card"
          style="
            border-radius: 10px;
            background-color: #ffffffad;
            margin-top: 5px;
            padding: 10px;
            height: 467px;
          "
        >
          <el-badge :value="registerNum" class="item" type="warning">
            <el-button
              size="small"
              @click="unconfirmVisible = true"
              type="warning"
              plain
              >审批</el-button
            >
          </el-badge>
          <el-button
            style="float: left"
            size="small"
            @click="generateInviteCode"
            type="success"
            plain
            >生成邀请码</el-button
          >
          注册用户一览
          <div
            id="searchGroup"
            style="
              float: right;
              width: 220px;
              height: 14px;
              font-size: 13px;
              margin-bottom: 2px;
            "
          >
            <el-input
              id="searchAccount"
              placeholder="输入账号精确检索"
              v-model="searchAccount"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="searchNormalAccount"
              ></el-button>
            </el-input>
          </div>
          <el-table
            height="384"
            :data="userList"
            style="width: 100%; background-color: #ffffffad"
          >
            <el-table-column
              prop="createTime"
              label="创建日期"
              width="129"
              header-align="center"
              align="center"
            >
            </el-table-column>
            <el-table-column prop="account" label="账号" width="240"> </el-table-column>
            <el-table-column prop="mail" label="邮箱"> </el-table-column>
            <el-table-column
              label="锁定/解锁"
              width="150"
              align="center"
              header-align="center"
            >
              <template slot-scope="scope">
                <el-switch
                  @change="changeSwitch(scope.row)"
                  v-model="scope.row.locked"
                  active-color="#ff6300"
                  inactive-color="#cfe9d0"
                >
                </el-switch
                >&nbsp;
              </template>
            </el-table-column>
          </el-table>
          <br />
          <el-pagination
            background
            layout="prev, pager, next"
            :total="pager.total"
            :current-page="pager.currentPage"
            @current-change="currentPageChange"
            :hide-on-single-page="hidePager"
            :page-size="7"
          >
          </el-pagination>
        </el-card>
      </el-col>
      <el-col :span="11"
        ><el-calendar
          v-model="date"
          style="border-radius: 10px; background-color: #ffffffad"
        >
        </el-calendar>
      </el-col>
    </el-row>

    <el-dialog
      :close-on-click-modal="false"
      title="修改个人信息"
      :visible.sync="updateDialog"
      :append-to-body="true"
      width="330px"
    >
      <el-divider content-position="left">昵称</el-divider>
      <el-input
        v-model="updNickName"
        autocomplete="off"
        :placeholder="nickName"
        prefix-icon="el-icon-user"
      ></el-input>
      <el-divider content-position="left">邮箱</el-divider>
      <el-input
        v-model="updMail"
        autocomplete="off"
        :placeholder="mail"
        prefix-icon="el-icon-message"
      ></el-input>
      <el-divider content-position="left">性别</el-divider>
      <el-radio-group v-model="updSexValue" size="mini">
        <el-radio-button label="1">帅哥(^_−)☆</el-radio-button>
        <el-radio-button label="0">美女(✪ω✪)</el-radio-button>
        <el-radio-button label="">未知(￣.￣)</el-radio-button>
      </el-radio-group>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateDialog = false" size="small" plain round
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="updateUserDetail"
          size="small"
          plain
          round
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      title="重置密码"
      :visible.sync="resetDialog"
      :append-to-body="true"
      width="330px"
    >
      <el-divider content-position="left">邮箱验证码</el-divider>
      <el-input
        v-model="mailCode"
        autocomplete="off"
        placeholder="输入邮箱验证码,点右边→_→"
        :disabled="mailCodeDisabled"
        prefix-icon="el-icon-message"
        maxlength="6"
        show-word-limit
      >
        <el-button
          slot="append"
          icon="el-icon-s-promotion"
          @click="sendMailCode"
        ></el-button>
      </el-input>
      <el-divider content-position="left">新密码</el-divider>
      <el-input
        v-model="newPassword"
        autocomplete="off"
        placeholder="输入新密码"
        prefix-icon="el-icon-key"
        type="password"
      ></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetDialog = false" size="small" plain round
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="resetPassword"
          size="small"
          plain
          round
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!--注册用户一览 -->
    <el-dialog
      width="750px"
      title="待确认审批的注册用户"
      :visible.sync="unconfirmVisible"
      :append-to-body="true"
    >
      <el-input
        id="unConfirmedAccount"
        placeholder="输入账号检索"
        v-model="unConfirmedAccount"
        style="
          float: left;
          width: 220px;
          height: 14px;
          font-size: 13px;
          margin-left: 10px;
        "
      >
        <el-button
          slot="append"
          icon="el-icon-search"
          @click="searchUnConfirmedAccount"
        ></el-button>
      </el-input>
      <el-button icon="el-icon-refresh-left" @click="clearSearch"></el-button>
      <el-table :data="unconfirmedUsers" height="520">
        <el-table-column
          property="createTime"
          label="申请日期"
          width="140"
        ></el-table-column>
        <el-table-column
          property="account"
          label="账号"
          width="200"
        ></el-table-column>
        <el-table-column property="mail" label="邮箱"></el-table-column>
        <el-table-column label="操作" align="center" width="80">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-check"
              circle
              plain
              size="mini"
              type="success"
              @click="accept(scope.row.id)"
            ></el-button>
            <el-popconfirm
              icon-color="red"
              @confirm="deny(scope.row.id)"
              title="拒绝这个用户的申请,确认吗?"
            >
              <el-button
                type="danger"
                icon="el-icon-close"
                circle
                size="mini"
                slot="reference"
              ></el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import storageUtil from "@/util/StorageUtil";
import axios from "@/util/AxiosUtil";
import apis from "@/util/ApiUrls";
import axiosStatic from "axios";

/**
 * 用户详情组件
 */
export default {
  name: "UserComponent",
  created() {
    const metaData = storageUtil.get();
    // 管理员则显示审批按钮
    this.showUsers = metaData.auth === "1";
    this.loading = true;
    axios
      .get(apis.api_auth.user)
      .then((user) => {
        // 用户数据
        this.nickName = user.data.nickName;
        this.updNickName = user.data.nickName;
        this.mail = user.data.mail;
        this.updMail = user.data.mail;
        this.sex = user.data.sex;
        this.sexValue = user.data.sexValue;
        this.updSexValue = user.data.sexValue;
      })
      .catch((e) => {
        this.$notify({
          title: "警告:获取用户数据失败",
          message: e.msg,
          type: "warning",
          duration: 1300,
        });
      })
      .finally(() => {
        this.loading = false;
      });

    // 如果是管理员则显示待审核的数据数量-每次最大99条
    // 显示用户一览数据
    if (this.showUsers) {
      this.getUsersTable();
    }
  },
  methods: {
    // 获取待审批的注册申请数量
    getUsersTable() {
      this.loading = true;
      // 聚合请求
      axiosStatic
        .all([
          axios.get(apis.api_auth.unconfirmedUsers),
          axios.get(apis.api_auth.users),
        ])
        .then(
          axiosStatic.spread((unconfirmedUsers, users) => {
            this.registerNum =
              unconfirmedUsers.data.length > 0
                ? unconfirmedUsers.data.length
                : "";
            this.unconfirmedUsers = unconfirmedUsers.data;
            this.cacheUsers = unconfirmedUsers.data;

            // 表格数据
            this.userList = users.data.userList ?? [];
            // 页数
            this.pager.total = users.data.total;
          })
        )
        .catch((e) => {
          this.$notify({
            title: "警告:获取用户列表失败",
            message: e.msg,
            type: "warning",
            duration: 1300,
          });
        })
        .finally(() => {
          this.loading = false;
          if (this.userList.length > 0) {
            // 有数据就显示分页
            this.hidePager = false;
          } else {
            this.hidePager = true;
          }
        });
    },
    // 点击分页组件切换页数触发
    currentPageChange(currentPage) {
      this.pager.currentPage = currentPage;
      this.searchAccountTable();
    },
    // 精确检索账户
    searchNormalAccount() {
      this.searchAccountTable();
    },
    // 检索账户一览表格数据
    searchAccountTable() {
      this.loading = true;
      axios
        .get(
          apis.api_auth.users +
            "?pageIndex=" +
            this.pager.currentPage +
            "&searchAccount=" +
            this.searchAccount
        )
        .then((users) => {
          this.userList = users.data.userList;
          if (!this.searchAccount) {
            this.pager.total = users.data.total;
          } else {
            this.pager.total = 0;
          }
        })
        .catch((e) => {
          this.$notify({
            title: "警告:检索待审核用户失败",
            message: e.msg,
            type: "warning",
            duration: 1300,
          });
        })
        .finally(() => {
          this.loading = false;
          // 没数据则隐藏分页
          this.hidePager = !(this.userList && this.userList.length > 0);
        });
    },
    // 清空检索待审批
    clearSearch() {
      this.unConfirmedAccount = "";
      // 从缓存中读取列表
      this.unconfirmedUsers = this.cacheUsers;
    },
    // 检索待审批的账户
    searchUnConfirmedAccount() {
      if (
        this.unConfirmedAccount === undefined ||
        this.unConfirmedAccount.trim().length === 0
      ) {
        this.$message({
          message: "请输入账号检索",
          type: "warning",
          duration: 1300,
        });
        return;
      }
      axios
        .get(
          apis.api_auth.unconfirmedUsers +
            "?unconfirmedAccount=" +
            this.unConfirmedAccount
        )
        .then((user) => {
          this.unconfirmedUsers = user.data;
        })
        .catch((e) => {
          this.$notify({
            title: "警告:检索待审核用户失败",
            message: e.msg,
            type: "warning",
            duration: 1300,
          });
        });
    },
    // 接受注册
    accept(id) {
      this.loading = true;
      axios
        .post(apis.api_auth.accept + "?id=" + id)
        .then(() => {
          this.$notify({
            title: "该用户的注册申请已被接受",
            type: "success",
            duration: 1300,
          });
          // 刷新表格数据
          this.getUsersTable();
        })
        .catch((e) => {
          this.$notify({
            title: "警告:处理失败",
            message: e.msg,
            type: "warning",
            duration: 1300,
          });
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 拒绝注册
    deny(id) {
      this.loading = true;
      axios
        .delete(apis.api_auth.deny + "?id=" + id)
        .then(() => {
          this.$notify({
            title: "该用户的注册申请已被拒绝",
            type: "success",
            duration: 1300,
          });
          // 刷新表格数据
          this.getUsersTable();
        })
        .catch((e) => {
          this.$notify({
            title: "警告:处理失败",
            message: e.msg,
            type: "warning",
            duration: 1300,
          });
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 生成邀请码
    generateInviteCode() {
      this.loading = true;
      axios
        .get(apis.api_auth.invitationCode)
        .then((res) => {
          this.$alert(
            "邀请码为: " + res.data,
            "邀请码60分钟后失效,关闭后不再显示",
            {
              confirmButtonText: "确定",
            }
          );
        })
        .catch((e) => {
          this.$notify({
            title: "警告:生成失败",
            message: e.msg,
            type: "warning",
            duration: 1300,
          });
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 锁定/解锁用户
    changeSwitch(row) {
      let locked = row.locked;
      // 未锁定-锁定
      if (locked) {
        row.locked = false;
        this.$confirm("将会锁定此用户,锁定后其无法登录, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.loading = true;
            axios
              .put(apis.api_auth.lockUser, { id: row.id })
              .then(() => {
                this.$notify({
                  title: "已锁定该用户",
                  type: "success",
                  duration: 1300,
                });
                row.locked = true;
              })
              .catch((e) => {
                this.$notify({
                  title: "警告:锁定失败",
                  message: e.msg,
                  type: "warning",
                  duration: 1300,
                });
              })
              .finally(() => {
                this.loading = false;
              });
          })
          .catch(() => {
            row.locked = false;
          });
      } else {
        // 解锁
        row.locked = true;
        this.$confirm("将会解锁此用户, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "info",
        })
          .then(() => {
            this.loading = true;
            axios
              .put(apis.api_auth.unlockUser, { id: row.id })
              .then(() => {
                this.$notify({
                  title: "已解锁该用户",
                  type: "success",
                  duration: 1300,
                });
                row.locked = false;
              })
              .catch((e) => {
                this.$notify({
                  title: "警告:锁定失败",
                  message: e.msg,
                  type: "warning",
                  duration: 1300,
                });
              })
              .finally(() => {
                this.loading = false;
              });
          })
          .catch(() => {
            row.locked = true;
          });
      }
    },
    // 显示dialog之前先赋值
    showUpdateDialog() {
      this.updNickName = this.nickName;
      this.updMail = this.mail;
      this.updSexValue = this.sexValue;
      this.updateDialog = true;
    },
    // 清空初始值
    initResetDialog() {
      this.resetDialog = true;
      this.mailCode = "";
      this.newPassword = "";
    },
    // 重置密码
    resetPassword() {
      if (!this.mailCode || this.mailCode.trim().length === 0) {
        this.$message({
          message: "验证码不能为空~请点击验证码发送按钮发送验证码",
          type: "warning",
          duration: 1500,
        });
        return;
      }

      if (!this.newPassword || this.newPassword.trim().length === 0) {
        this.$message({
          message: "新密码不能为空~",
          type: "warning",
          duration: 1500,
        });
        return;
      }

      this.loading = true;
      axios
        .put(apis.api_auth.password, {
          password: this.newPassword,
          code: this.mailCode,
        })
        .then(() => {
          this.$notify({
            title: "密码修改成功,下次登录时生效",
            type: "success",
            duration: 1300,
          });

          // 禁用验证码输入框
          this.mailCodeDisabled = true;
          // 清空状态
          this.newPassword = "";
          this.mailCode = "";
          this.resetDialog = false;
        })
        .catch((e) => {
          this.$notify({
            title: "警告:密码修改失败",
            message: e.msg,
            type: "warning",
            duration: 1300,
          });
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 发送验证码
    sendMailCode() {
      this.loading = true;
      axios
        .post(apis.api_auth.mailCode)
        .then(() => {
          this.$notify({
            title: "验证码已发送至" + this.mail + ",请注意查收",
            type: "success",
            duration: 1300,
          });
          // 可以输入验证码了
          this.mailCodeDisabled = false;
        })
        .catch((e) => {
          this.$notify({
            title: "警告:验证码发送失败",
            message: e.msg,
            type: "warning",
            duration: 1300,
          });
        })
        .finally(() => {
          this.loading = false;
        });
    },
    updateUserDetail() {
      // check
      if (
        this.updNickName === undefined ||
        this.updNickName.trim().length === 0
      ) {
        this.$message({
          message: "昵称不能为空~",
          type: "error",
          duration: 1500,
        });
        return;
      }
      if (this.updMail === undefined || this.updMail.trim().length === 0) {
        this.$message({
          message: "邮箱不能为空~",
          type: "error",
          duration: 1500,
        });
        return;
      } else if (
        !/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(this.updMail)
      ) {
        this.$message({
          message: "请输入合法的邮箱~",
          type: "error",
          duration: 1500,
        });
        return;
      }
      // 什么都没变的情况下不请求后台
      if (
        this.updMail === this.mail &&
        this.updNickName === this.nickName &&
        this.updSexValue === this.sexValue
      ) {
        this.updateDialog = false;
        return;
      }

      this.loading = true;
      axios
        .put(apis.api_auth.user, {
          nickName: this.updNickName,
          mail: this.updMail,
          sexValue: this.updSexValue,
        })
        .then((res) => {
          this.nickName = res.data.nickName;
          this.mail = res.data.mail;
          this.sex = res.data.sex;
          this.sexValue = res.data.sexValue;
          this.updateDialog = false;
        })
        .catch((e) => {
          this.$notify({
            title: "警告:更新用户详情失败",
            message: e.msg,
            type: "warning",
            duration: 1300,
          });
        })
        .finally(() => {
          this.loading = false;
        });
    },
  },
  data() {
    return {
      updMail: "", // 更新的邮箱
      updNickName: "", // 更新的昵称
      updSexValue: "", // 更新的性别值
      updateDialog: false, // 修改个人信息的弹框
      resetDialog: false, // 重置密码弹框
      loading: false,
      nickName: storageUtil.getItem("nickname"),
      mail: "",
      sex: "", // 显示的性别值
      sexValue: "", // 实际性别值
      mailCode: "", // 邮箱验证码
      newPassword: "", // 新密码
      mailCodeDisabled: true, // 发送验证码后才能输入验证码
      date: new Date(),
      userList: [], // 用户列表
      registerNum: "", // 注册后待审批的数量
      showUsers: false, // 是否显示用户一览数据
      unconfirmedUsers: [], // 申请注册的用户一览
      unconfirmVisible: false, // 待确认申请的注册用户一览对话框
      unConfirmedAccount: "", // 检索条件-待审批的账户
      cacheUsers: [], // 审批列表检索后的数据缓存
      pager: {
        total: 0,
        currentPage: 1,
      },
      hidePager: false,
      searchAccount: "", // 检索账户
    };
  },
};
</script>


<style scope>
#userDetail .my-label {
  background-color: #dcf2f16b !important;
  width: 100px;
}

#userDetail .my-content {
  background: #e2d98533;
  width: 200px;
}

#userDetail .el-dialog__body {
  padding: 0 20px;
}

#userDetail .el-descriptions {
  padding: 10px;
}

#userDetail div.el-card__body .el-badge {
  float: left;
}

#userDetail table tr,
#userDetail table tr th {
  background-color: #ffffff00;
}

#userDetail input#searchAccount {
  height: 32px;
  background-color: #e3fbe9b3;
}

#userDetail #searchGroup .el-input-group__append {
  background-color: #f6edc2;
}
</style>